#include <iostream>
#include "tclientthread.h"
#include <game/game.h>

using namespace std;

#define STR(s) ( (QTextCodec::codecForLocale() -> fromUnicode(s)).constData() )
using namespace std;

TClientThread::TClientThread(QObject* parent) :
    QThread(parent)
{
    host   = "localhost";
    port   = 1066;
    socket = NULL;
}

bool TClientThread::connectToHost(){
    if(socket == NULL){
        socket = new QTcpSocket();
        socket->deleteLater();
    }

    if(socket->state() == QAbstractSocket::ConnectedState){
        return true;
    }

    socket->connectToHost(host, port);
    if(!socket->waitForConnected(5000)){
        return false;
    }

    return true;
}

bool TClientThread::readData(){
    if(!socket->waitForReadyRead(5000)){
        return false;
    }
    Game::Instance() -> write(socket->readAll().data());
    return true;
}

bool TClientThread::writeData(){
    if(socket->write(Game::Instance() -> read()) < 0){
        return false;
    }
    return true;
}

void TClientThread::run(){
    forever{
        exchangeData();
        sleep(1);
    }
}

void TClientThread::exchangeData(){
    if(!connectToHost() || !readData() || !writeData()) quit();
}
